//
//  CommentVC.m
//  NtoccShipper
//
//  Created by mac on 2019/12/5.
//  Copyright © 2019 zhuchongjin. All rights reserved.
//

#import "CommentVC.h"
#import "HCSStarRatingView.h"
#import "HDPicModle.h"
#import "GetPhoto.h"
#import "XLImageViewer.h"
#import "UpLoadImageCell.h"
#import "UploadImgModel.h"


static NSString* reuseCellIdentifier = @"UpLoadImageCell";

@interface CommentVC ()<UICollectionViewDelegate,
UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property (nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic,strong) NSMutableArray *arrModel;
@property (nonatomic,strong) CJButton *btnSave;


@property (nonatomic,strong) CJImageView *imgVAbnormal;
//@property (nonatomic,copy) NSString *strAbnormal; // 0 1异常
@property (nonatomic,strong) CJLabel *labReturnOrderImgIndex;
@property (nonatomic,strong) FlexTextView *textView;
@property (nonatomic,strong) CJView *viewDelivery; //  运输效率
@property (nonatomic,strong) HCSStarRatingView *viewStarDelivery; //运输效率
@property (nonatomic,copy) NSString *strSpeed;
// safetyGrade 运输安全
@property (nonatomic,strong) CJView *viewSafety; //
@property (nonatomic,strong) HCSStarRatingView *viewStarSafetyGrade; //
@property (nonatomic,copy) NSString *strSafety;
// 服务质量
@property (nonatomic,strong) CJView *viewStarServer;
@property (nonatomic,strong) HCSStarRatingView *viewRateServer;
@property (nonatomic,copy) NSString *strServer;
//货物损耗   goodsLoss
@property (nonatomic,strong) CJView *viewGoodsLoss;
@property (nonatomic,strong) HCSStarRatingView *viewStarGoodsLoss;
@property (nonatomic,copy) NSString *strGoodsLoss;
// 客户满意度   satisfactionGrade
@property (nonatomic,strong) CJView *viewSatisfaction;
@property (nonatomic,strong) HCSStarRatingView *viewRateSatisfaction;
@property (nonatomic,copy) NSString *strSatisfaction;
@property (nonatomic,strong) FlexTouchView *touchViewAddimg;
@end
 //  运输效率、运输安全、服务质量、客户满意度
@implementation CommentVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setTitleName:CJLString(@"评价司机")];
    [self setBackLeftButton:@""];
    self.view.backgroundColor = [UIColor cjWhiteColor];
//    [self setSecondAppNavigationBarStyle];

    self.arrModel = [[NSMutableArray alloc]init];
    for (int i = 0; i < 1; i++) {
        UploadImgModel *model = [[UploadImgModel alloc]init];
        model.strImgUrl = @"";
        model.strTitle = @"";
        model.changeImg = NO;
        model.hideDeleteImg = YES;
        [self.arrModel addObject:model];
    }
    [self createView];
    
    
    // 默认 5✨
    self.strServer = @"5";
    self.strSpeed = @"5";
    self.strSafety = @"5";
    self.strGoodsLoss = @"5";
    self.strSatisfaction = @"5";
    _viewRateServer.value = 5;
    _viewRateSatisfaction.value = 5;
    _viewStarSafetyGrade.value = 5;
    _viewStarGoodsLoss.value = 5;
    _viewStarDelivery.value = 5;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
//    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}

/// 创
- (void)createView{

    CGRect rcFrame = CGRectMake(0, kTopHeight, kScreenWidth, 0);
    FlexFrameView *header = [[FlexFrameView alloc] initWithFlex:@"CommentTopView" Frame:rcFrame Owner:self];
    header.flexibleHeight = YES;

//    运输效率
    [self.viewDelivery addSubview:self.viewStarDelivery];
    [self.viewStarDelivery addTarget:self action:@selector(didChangeAbnormalValue:) forControlEvents:UIControlEventValueChanged];
//    // 服务质量
    [self.viewStarServer addSubview:self.viewRateServer];
    [self.viewRateServer addTarget:self action:@selector(didChangeServerValue:) forControlEvents:UIControlEventValueChanged];
//    // safetyGrade 运输安全
    [self.viewSafety addSubview:self.viewStarSafetyGrade];
    [self.viewStarSafetyGrade addTarget:self action:@selector(didChangeStarSafetyGrade:) forControlEvents:UIControlEventValueChanged];
    //    // 货物损耗
    [self.viewGoodsLoss addSubview:self.viewStarGoodsLoss];
    [self.viewStarGoodsLoss addTarget:self action:@selector(didChangeviewStarGoodsLoss:) forControlEvents:UIControlEventValueChanged];
    
//    客户满意度
    [self.viewSatisfaction addSubview:self.viewRateSatisfaction];
    [self.viewRateSatisfaction addTarget:self action:@selector(didChangeRateSatisfaction:) forControlEvents:UIControlEventValueChanged];

    [header layoutIfNeeded];
    [self.view addSubview:header];
    [self.view addSubview:self.collectionView];

    self.collectionView.frame = CGRectMake(10, kTopHeight + header.height, kScreenWidth -20, kScreenHeight - kTopHeight - header.height -50);
    [self.view addSubview:self.btnSave];
    
    [self.collectionView reloadData];
    
}

- (void)didChangeServerValue:(HCSStarRatingView *)sender {
    NSLog(@"Changed rating to %.1f", sender.value);
    self.strServer = CJStringWithFormat(@"%.1f",sender.value);
}

- (void)didChangeAbnormalValue:(HCSStarRatingView *)sender {
    NSLog(@"Changed Abnormal to %.1f", sender.value);
    self.strSpeed = CJStringWithFormat(@"%.1f",sender.value);
}

- (void)didChangeStarSafetyGrade:(HCSStarRatingView *)sender {
    NSLog(@"didChangeStarSafetyGrade %.1f", sender.value);
    self.strSafety = CJStringWithFormat(@"%.1f",sender.value);
}

/// 货物损耗
/// @param sender <#sender description#>
- (void)didChangeviewStarGoodsLoss:(HCSStarRatingView *)sender {
    NSLog(@"strSatisfaction %.1f", sender.value);
    self.strGoodsLoss = CJStringWithFormat(@"%.1f",sender.value);
}

- (void)didChangeRateSatisfaction:(HCSStarRatingView *)sender {
    NSLog(@"strSatisfaction %.1f", sender.value);
    self.strSatisfaction = CJStringWithFormat(@"%.1f",sender.value);
}

#pragma mark ----------提交数据
- (void)saveCommitInfoAvtion{
//    [CJAlert showStringDismissWithDelay:@"隐私协议"];
    
    if (self.textView.text.length == 0) {
           [CJAlert showStringDismissWithDelay:@"请填写评论内容"];
           return;
       }
    
    if (self.textView.text.length > 255) {
        [CJAlert showStringDismissWithDelay:@"评论内容过长"];
        return;
    }else{
        
        __block NSString *strImgs = @"";
        if ([self getArrImgsWitHArrModel:self.arrModel].count > 0) {
            [[self getArrImgsWitHArrModel:self.arrModel] enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (idx == 0) {
                    strImgs = obj;
                }else{
                    strImgs = CJStringWithFormat(@"%@,%@",strImgs,obj);
                }
            }];
        }
        
        NSString *strURL = CJStringWithFormat(@"%@/ntocc-basic-api/orderComment",CJBaseUrl);
        NSDictionary *dicPar = @{
            @"imageUrl":strImgs,
            @"orderCode":self.strCode,
            @"serviceGrade":self.strServer,
            @"speedGrade":self.strSpeed,
            @"commentContent":self.textView.text,
            @"commentType":@"0",
            @"safetyGrade":self.strServer,
            @"satisfactionGrade":self.strSatisfaction,
            @"lossGrade":self.strGoodsLoss
        };
        
        WS(ws);
        [[HDNetworking sharedHDNetworking] dataTaskWithHTTPMethod:PostType url:strURL parameters:dicPar status:OperationTip success:^(id  _Nonnull responseObject) {
            if (ws.blockSuccess) {
                ws.blockSuccess(@"");
                [ws pop];
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
        
    }
}


#pragma mark collectionView代理方法
//返回section个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

//每个section的item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    if (self.arrModel.count >= 10) {
        return 9;
    }else{
        return self.arrModel.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    UpLoadImageCell *cell = (UpLoadImageCell *)[collectionView dequeueReusableCellWithReuseIdentifier:reuseCellIdentifier forIndexPath:indexPath];
    
    UploadImgModel *model = self.arrModel[indexPath.row];
    [cell setCellWithModel:model index:indexPath.row arrSum:self.arrModel.count];
    WS(ws);
    cell.blockDelete = ^(id anyObject) {
        [ws btnActionDelecteImgWithIndex:indexPath];
    };
    return cell;
}

- (void)btnActionDelecteImgWithIndex:(NSIndexPath *)indexPath{
    
//    // 删除2个
//    if (indexPath.row <= 1) {
//        UploadImgModel *model = self.arrModel[indexPath.row];
//        model.strImgUrl = @"";
//        model.hideDeleteImg = YES;
//        [self.arrModel replaceObjectAtIndex:indexPath.row withObject:model];
//    }else{
        [self.arrModel removeObjectAtIndex:indexPath.row];
//    }
    [self.collectionView reloadData];
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
//    NSLog(@"selected: %d",(int)indexPath.row);
    UploadImgModel *modInfo = self.arrModel[indexPath.row];
    
    if (modInfo.changeImg && ![modInfo.strImgUrl isEqualToString:@""]) {
        [self selelctChangeImgVOrSeeBigPicWitnIndex:indexPath.row isLast:NO];
    }else{

        if (self.arrModel.count == 10) {
            [CJAlert showStringDismissWithDelay:@"最多只能上传9张图片"];
            return;
        }
        if (indexPath.row + 1 == self.arrModel.count) {
            UploadImgModel *model = [[UploadImgModel alloc]init];

            model.changeImg = NO;
            [self.arrModel addObject:model];
//            DLog(@"===== 点击最后一个");
        }
        [self btnUploadImgVWitnIndex:indexPath.row isLast:NO];
//        }
    }
}

//设置每个item的尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(80, 80);
}
//设置每个item水平间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 20;
}

//设置每个item垂直间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 15;
}


#pragma mark ---------上传图片相关

- (void)selelctChangeImgVOrSeeBigPicWitnIndex:(NSInteger )index isLast:(BOOL)isLast{
    
    WS(ws);
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *change = [UIAlertAction actionWithTitle:@"更换照片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        [ws uploadImgV];
        [ws btnUploadImgVWitnIndex:index isLast:isLast];
    }];
    UIAlertAction *seeBig = [UIAlertAction actionWithTitle:@"查看大图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[XLImageViewer shareInstanse] showNetImages:[ws getArrImgsWitHArrModel:self.arrModel] index:index fromImageContainer:ws.view];
    }];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [alertVC dismissViewControllerAnimated:NO completion:^{
    
        }];
    }];

    [alertVC addAction:change];
    [alertVC addAction:seeBig];
    [alertVC addAction:cancle];
    [self presentViewController:alertVC animated:YES completion:nil];
    
}

// 上传图片
- (void)btnUploadImgVWitnIndex:(NSInteger )index isLast:(BOOL)isLast{
    
    WS(ws);
    [GetPhoto getPhoto:self completion:^(UIImage *curImage, NSData *imageData) {
        
        [ws upLoadReturnImageUImage:curImage withNSData:imageData withIndex:index isLast:isLast];
    }];
}

- (void)upLoadReturnImageUImage:(UIImage *)img withNSData:(NSData *)imageData withIndex:(NSInteger )index isLast:(BOOL)isLast{

    NSString *strURL = CJStringWithFormat(@"%@/ntocc-tps-api/fileUpload",CJBaseUrl);
    NSURL *str = [[NSURL alloc]initFileURLWithPath:[CJControl getImgFilePath:img]];
    NSDictionary *dic = @{
                          @"file":str
                          };
    HDPicModle *model = [[HDPicModle alloc]init];
    model.pic = img;
    model.picData = imageData;
    model.picName = @"file";
    model.fileName = [CJControl getImgFilePath:img];

    WS(ws);
    [[HDNetworking sharedHDNetworking] POST:strURL parameters:dic andPic:model progress:^(NSProgress * _Nullable progress) {
//        DLog(@"%lf", 1.0 * progress.completedUnitCount / progress.totalUnitCount);
    } success:^(id  _Nonnull responseObject) {

        NSString *strStatus = CJStringWithFormat(@"%@",responseObject[@"status"]);
        NSString *strImgVUrl = [CJControl getThreeUnaryValueStr:responseObject[@"data"]];

        if (strStatus.integerValue == 0) {
            UploadImgModel *model = ws.arrModel[index];
            model.strImgUrl = strImgVUrl;
            model.changeImg = YES;
            model.hideDeleteImg = NO;
            [ws.arrModel replaceObjectAtIndex:index withObject:model];

        }

        [self.collectionView reloadData];

    } failure:^(NSError * _Nonnull error) {
        DLog(@"+++++++%@",error);

    }];
}

- (NSMutableArray *)getArrImgsWitHArrModel:(NSMutableArray *)arr{
    
    NSMutableArray *arrImgs = [[NSMutableArray alloc]init];
    NSUInteger y;
    if (arr.count >9) {
        y = 9;
    }else{
        y = arr.count;
    }
    
    for (int i = 0; i < y; i++) {
        
        UploadImgModel *model = arr[i];
        if ([CJControl getIsEmpty:model.strImgUrl]) {
        }else{
            [arrImgs addObject:[CJControl getThreeUnaryValueStr:model.strImgUrl]];
        }
      
    }
    return arrImgs;
}
#pragma mark ----------lazy----

- (UICollectionView *)collectionView{
    
    if (!_collectionView) {
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        _collectionView =[[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.frame = CGRectMake(10, kTopHeight, kScreenWidth -20, kScreenHeight - kTopHeight);
        [_collectionView registerClass:UpLoadImageCell.class forCellWithReuseIdentifier:reuseCellIdentifier];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = [UIColor cjWhiteColor];
        
//        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeaderwithReuseIdentifier:@"header"];
        
    }
    return _collectionView;
}

- (CJButton *)btnSave{
    
    if (!_btnSave) {
        _btnSave = CJButton.btnInit
        .btnFrame(CGRectMake(0,self.collectionView.bottom,kScreenWidth, 50))
        .btnBgColor([UIColor cjMainColor])
        .btnTargetAction(self, @selector(saveCommitInfoAvtion))
        .btnText(@"发布")
        .btnFont([UIFont cjTitleFont17])
        ;
    }
    
    return _btnSave;
}
- (HCSStarRatingView *)viewRateServer{
    if (!_viewRateServer) {
      _viewRateServer =   [[HCSStarRatingView alloc]initWithFrame:CGRectMake(0,0,120 ,35)];
        _viewRateServer.tintColor = [UIColor cjStarRateColor];
        _viewRateServer.starBorderColor = [UIColor cjClearColor];
        _viewRateServer.emptyStarColor = [UIColor cjEmptyStarRateColor];
        _viewRateServer.backgroundColor = [UIColor cjClearColor];
//        _viewRate.enabled = NO;
        _viewRateServer.starBorderColor = [UIColor cjClearColor];
        _viewRateServer.emptyStarColor = [UIColor cjEmptyStarRateColor];
//        _viewRateServer.tintColor = [UIColor cjStarRateColor];
        _viewRateServer.allowsHalfStars = NO;
        _viewRateServer.maximumValue = 5;
        _viewRateServer.minimumValue = 0;
    }
    return  _viewRateServer;
}

- (HCSStarRatingView *)viewStarDelivery{
    if (!_viewStarDelivery) {
      _viewStarDelivery =   [[HCSStarRatingView alloc]initWithFrame:CGRectMake(0,0,120 ,35)];
        _viewStarDelivery.tintColor = [UIColor cjStarRateColor];
        _viewStarDelivery.starBorderColor = [UIColor cjClearColor];
        _viewStarDelivery.emptyStarColor = [UIColor cjEmptyStarRateColor];
        _viewStarDelivery.backgroundColor = [UIColor cjClearColor];
//        _viewRate.enabled = NO;
        _viewStarDelivery.allowsHalfStars = NO;
        _viewStarDelivery.maximumValue = 5;
        _viewStarDelivery.minimumValue = 0;
    }
    return  _viewStarDelivery;
}

- (HCSStarRatingView *)viewStarSafetyGrade{
    if (!_viewStarSafetyGrade) {
      _viewStarSafetyGrade =   [[HCSStarRatingView alloc]initWithFrame:CGRectMake(0,0,120 ,35)];
        _viewStarSafetyGrade.tintColor = [UIColor cjStarRateColor];
        _viewStarSafetyGrade.starBorderColor = [UIColor cjClearColor];
        _viewStarSafetyGrade.emptyStarColor = [UIColor cjEmptyStarRateColor];
        _viewStarSafetyGrade.backgroundColor = [UIColor cjClearColor];
//        _viewRate.enabled = NO;
        _viewStarSafetyGrade.allowsHalfStars = NO;
        _viewStarSafetyGrade.maximumValue = 5;
        _viewStarSafetyGrade.minimumValue = 0;
    }
    return  _viewStarSafetyGrade;
}

/// 货物损耗度
- (HCSStarRatingView *)viewStarGoodsLoss{
    if (!_viewStarGoodsLoss) {
      _viewStarGoodsLoss =   [[HCSStarRatingView alloc]initWithFrame:CGRectMake(0,0,120 ,35)];
        _viewStarGoodsLoss.tintColor = [UIColor cjStarRateColor];
        _viewStarGoodsLoss.starBorderColor = [UIColor cjClearColor];
        _viewStarGoodsLoss.emptyStarColor = [UIColor cjEmptyStarRateColor];
        _viewStarGoodsLoss.backgroundColor = [UIColor cjClearColor];
//        _viewRate.enabled = NO;
        _viewStarGoodsLoss.allowsHalfStars = NO;
        _viewStarGoodsLoss.maximumValue = 5;
        _viewStarGoodsLoss.minimumValue = 0;
    }
    return  _viewStarGoodsLoss;
}

- (HCSStarRatingView *)viewRateSatisfaction{
    if (!_viewRateSatisfaction) {
      _viewRateSatisfaction =   [[HCSStarRatingView alloc]initWithFrame:CGRectMake(0,0,120 ,35)];
        _viewRateSatisfaction.tintColor = [UIColor cjStarRateColor];
        _viewRateSatisfaction.starBorderColor = [UIColor cjClearColor];
        _viewRateSatisfaction.emptyStarColor = [UIColor cjEmptyStarRateColor];
        _viewRateSatisfaction.backgroundColor = [UIColor cjClearColor];
//        _viewRate.enabled = NO;
        _viewRateSatisfaction.allowsHalfStars = NO;
        _viewRateSatisfaction.maximumValue = 5;
        _viewRateSatisfaction.minimumValue = 0;
    }
    return  _viewRateSatisfaction;
}



@end
